package com.jinke.api.modules.third.carryship.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.annotation.Apilog;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.modules.third.carryship.model.request.*;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.third.ezeeship.util.EzeeShipUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class CarryshipUtil {

    public static final String CREATE_WAYBILL = "http://www.carry-ship.com/interface/api/v1/createWaybill";
    public static final String APPLY_REFUND = "http://www.carry-ship.com/interface/api/v1/applyRefund";
    public static final String TRACKING_PHP = "https://sj.tanwapost.com/xapi/tracking.php";
    public static final String CHANNEL_PHP = "https://sj.tanwapost.com/xapi/channel.php";
    public static final String API_TOKEN = "http://www.carry-ship.com/oauth2/api/token";
    public static final String RATE = "http://www.carry-ship.com/interface/api/v1/operation";
    public static String accessToken = "";

    private String sendPostRequest(String url, String requestBody) throws IOException {
        return sendPostRequest(url, requestBody, "application/json");
    }

    private String sendPostRequest(String url, String requestBody, String contentType) throws IOException {
        HttpURLConnection connection = null;
        try {

            // 创建连接
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }


            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Authorization", "Bearer " + accessToken);
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream outputStream = connection.getOutputStream()) {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                writer.write(requestBody);
                writer.flush();
            }

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private String sendGetRequest(String url) throws IOException {
        HttpURLConnection connection = null;
        try {
            String seq = CommonUtil.getOrderNo();
            log.info("send :  {}, {}", seq, url);
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Basic RVpBS2E5Y2UxM2FhNDVhNzQ5N2JiMGI1ZTZiOGY2Y2E0Y2RiRkdGM0dnT3UwU3ZHN0VrNURHc3RKdw==");
            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("rec :  {}, {}", seq, response.toString());
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }



    public void getetToken() {
        String param = "appId=3&grant_type=client_credentials&client_id=ZHPLEUBCORQ&client_secret=KWOHYLOMVED";

        try {
            String sendPostRequest = sendPostRequest(API_TOKEN, param, "application/x-www-form-urlencoded");
            if (StringUtils.isNotEmpty(sendPostRequest)) {
                JSONObject jsonObject = JSON.parseObject(sendPostRequest);
                String accessTokenObj = jsonObject.getString("accessToken");
                if (StringUtils.isNotEmpty(accessTokenObj)) {
                    accessToken = accessTokenObj;
                }
            }
            System.out.println(accessToken);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


     @Apilog(requestTypeName = "CarryShip-估价")
    public String getPrice(EstimateRateRequest estimateRateRequest) {
        CreateOrderRequest createOrderRequest = getCreateOrderRequest(estimateRateRequest);
        String orderNO = estimateRateRequest.getOrderNO();
        try {
            // 发送POST请求
            String param = JSON.toJSONString(createOrderRequest);
            log.info("-----------CarryShip估价请求参数------------>,{},{}", orderNO, param);
            String response = sendPostRequest(RATE, param);
            log.info("-----------CarryShip估价返回参数------------>,{},{}", orderNO, response);
            return response;
        } catch (IOException e) {
            log.info("-----------CarryShip估价返回参异常------------>,{}", orderNO,e.getMessage());
        }
        return Strings.EMPTY;
    }

    @Apilog(requestTypeName = "CarryShip-下单")
    public String createOrder(EstimateRateRequest estimateRateRequest) {
        String orderNO = estimateRateRequest.getOrderNO();
        CreateOrderRequest createOrderRequest = getCreateOrderRequest(estimateRateRequest);
        try {
            // 发送POST请求
            String param = JSON.toJSONString(estimateRateRequest);
            log.info("-----------CarryShip下单请求参数------------>,{},{}", orderNO, param);

            String response = sendPostRequest(CREATE_WAYBILL, param);
            log.info("-----------CarryShip下单返回参数------------>,{},{}", orderNO, response);

            return response;
        } catch (IOException e) {
            log.info("-----------CarryShip下单异常------------>,{}", e.getMessage());
        }
        return Strings.EMPTY;
    }


    @NotNull
    private CreateOrderRequest getCreateOrderRequest
            (EstimateRateRequest estimateRateRequest) {
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();

        CreateOrderRequest.ConfirmChannels confirmChannels = new CreateOrderRequest.ConfirmChannels();
        confirmChannels.setChannelsCode(estimateRateRequest.getServiceCode());
        createOrderRequest.setConfirmChannels(confirmChannels);
        CreateOrderRequest.Address sender = new CreateOrderRequest.Address();

        // 创建地址
        EstimateRateRequest.Address from = estimateRateRequest.getFrom();
        sender.setName(from.getPersonName());
        sender.setCountry(from.getCountryCode());
        sender.setPhone(from.getPhone());
        sender.setCity(from.getCity());
        sender.setProvince(from.getStateCode());
        sender.setPostalCode(from.getZipCode());
        sender.setAddress1(from.getAddressLine1());
        sender.setAddress2(from.getAddressLine2());
        createOrderRequest.setSendInfo(sender);

        CreateOrderRequest.Address recipient = new CreateOrderRequest.Address();
        EstimateRateRequest.Address to = estimateRateRequest.getTo();
        recipient.setName(to.getPersonName());
        recipient.setCountry(to.getCountryCode());
        recipient.setPhone(to.getPhone());
        recipient.setCity(to.getCity());
        recipient.setProvince(to.getStateCode());
        recipient.setPostalCode(to.getZipCode());
        recipient.setAddress1(to.getAddressLine1());
        recipient.setAddress2(to.getAddressLine2());
        // recipient.setResidential(to.getIsResidential());
        createOrderRequest.setGetInfo(recipient);

        // 只支持单包裹
        List<EstimateRateRequest.Parcel> parcels = estimateRateRequest.getParcels();
        List<CreateOrderRequest.Package> packages = parcels.stream().map(x -> {
            // 创建Parcels对象
            CreateOrderRequest.Package p = new CreateOrderRequest.Package();
            //  parcels.setBoxnote("label reference");
            BigDecimal weight = BigDecimal.valueOf(Double.parseDouble(x.getWeight()));
            //
            String weightUtil = x.getMassUnit();
            if ("lb".equals(weightUtil)) {
                weightUtil = "LBS";
            }
            p.setWeightUnit(weightUtil);
            p.setWeight(weight);

            // 转换成in
            BigDecimal length = BigDecimal.valueOf(Double.parseDouble(x.getLength()));
            BigDecimal width = BigDecimal.valueOf(Double.parseDouble(x.getWidth()));
            BigDecimal height = BigDecimal.valueOf(Double.parseDouble(x.getHeight()));

            p.setLength(length);
            p.setWidth(width);
            p.setHeight(height);
            p.setSizeUnit(x.getDistanceUnit());
            p.setQuantity(BigDecimal.ONE);
            return p;
        }).collect(Collectors.toList());
        createOrderRequest.setPackages(packages);


//        EstimateRateRequest.LabelExtra extra = estimateRateRequest.getExtra();
//        String reference = "1";
//        if (extra != null) {
//            reference = extra.getReference();
//            if (StringUtils.isNotBlank(reference) && StringUtils.isNotEmpty(extra.getReference2())) {
//                reference = reference + "; " + extra.getReference2();
//            }
//
//        }
        createOrderRequest.setReference(estimateRateRequest.getOrderNO());
        return createOrderRequest;
    }


    public String cancelLabel(String objectId) {
        // 设置API端点URL

        CancelRequest request = new CancelRequest();
        request.setReferenceNoOne(objectId);
        String requestBody = JSON.toJSONString(request);

        try {
            // 发送POST请求
            System.out.println(requestBody);
            String response = sendGetRequest(APPLY_REFUND);
            // 处理响应
            System.out.println("Response: " + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public String tracking(String tracingNo) {
        // 设置API端点URL

        TrackingRequest request = new TrackingRequest();
        request.setTrackingno(tracingNo);
        request.setApikey("tw_4838");
        String requestBody = JSON.toJSONString(request);

        try {
            // 发送POST请求
            System.out.println(requestBody);
            String response = sendPostRequest(TRACKING_PHP, requestBody);
            // 处理响应
            System.out.println("Response: " + response);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    public String getChannel() {
        // 设置API端点URL

        // 将OrderRequest对象转换为JSON字符串
        // 创建OrderRequest对象
        BaseEntity orderRequest = new BaseEntity();

// 设置属性值
        orderRequest.setApikey("tw_4838");

        String requestBody = JSON.toJSONString(orderRequest);

        try {
            // 发送POST请求
            System.out.println();
            String response = sendPostRequest(CHANNEL_PHP, requestBody);
            System.out.println("Response: " + response);
            // 处理响应
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


}
